package cn.dao;

import cn.comon.DBConnection;
import cn.entity.PayDetail;

import javax.swing.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class PayDetailDao implements AutoCloseable {

    private Connection conn;

    public PayDetailDao() {
        conn = new DBConnection().getConn();
    }

    public List<Object[]> selectAll() {
        List<Object[]> data = new ArrayList<>();
        String sql = "SELECT * FROM paydetail"; // 假设支付明细表名为'pay_details'
        try (Statement sta = conn.createStatement();
             ResultSet rs = sta.executeQuery(sql)) {
            while (rs.next()) {
                Object[] rowData = new Object[7]; // 假定支付明细有7个字段
                rowData[0] = rs.getInt(1); // Did
                rowData[1] = rs.getInt(2); // Mid
                rowData[2] = rs.getString(3); // Gid
                rowData[3] = rs.getInt(4); // Dcount
                rowData[4] = rs.getFloat(5); // Price
                rowData[5] = rs.getFloat(6); // GoodsTotal
                rowData[6] = rs.getString(7); // Notes
                data.add(rowData);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return data;
    }


    public void addPayDetail(List<PayDetail> payDetailsList) {
        String checkDidSql = "SELECT COUNT(*) FROM PayMain WHERE Mid = ?";
        String checkGidSql = "SELECT COUNT(*) FROM Goods WHERE Gid = ?";
        String insertSql = "INSERT INTO PayDetail (Did, Mid, Gid, DCount, Notes) VALUES (?, ?, ?, ?, ?)";

        try (PreparedStatement checkDidStmt = conn.prepareStatement(checkDidSql);
             PreparedStatement checkGidStmt = conn.prepareStatement(checkGidSql);
             PreparedStatement insertStmt = conn.prepareStatement(insertSql)) {

            conn.setAutoCommit(false);

            for (PayDetail payDetail : payDetailsList) {
                // 检查Did是否存在
                checkDidStmt.setInt(1, payDetail.getMid());
                ResultSet rsDid = checkDidStmt.executeQuery();
                rsDid.next();
                int countDid = rsDid.getInt(1);

                // 检查Gid是否存在
                checkGidStmt.setString(1, payDetail.getGid());
                ResultSet rsGid = checkGidStmt.executeQuery();
                rsGid.next();
                int countGid = rsGid.getInt(1);

                if (countDid == 0) {
                    JOptionPane.showMessageDialog(null, "清单编号(" + payDetail.getDid() + ")不存在，请检查后重试！", "错误", JOptionPane.ERROR_MESSAGE);
                    throw new SQLException("DID not found in PayMain table.");
                }

                if (countGid == 0) {
                    JOptionPane.showMessageDialog(null, "商品编号(" + payDetail.getGid() + ")不存在，请检查后重试！", "错误", JOptionPane.ERROR_MESSAGE);
                    throw new SQLException("GID not found in Goods table.");
                }

                // 两者都存在，则执行插入操作
                insertStmt.setInt(1, payDetail.getDid());
                insertStmt.setInt(2, payDetail.getMid());
                insertStmt.setString(3, payDetail.getGid());
                insertStmt.setInt(4, payDetail.getDcount());
                insertStmt.setString(5, payDetail.getNotes());
                insertStmt.addBatch();
            }

            // 确保有数据再执行批处理
            if (!payDetailsList.isEmpty()) {
                insertStmt.executeBatch();
            }
            conn.commit();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            JOptionPane.showMessageDialog(null, "插入支付明细时发生错误: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }

    public void deletePayDetail(int did) {
        String sql = "DELETE FROM paydetail WHERE did = ?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, did);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updatePayDetail(PayDetail payDetail, String originalDid) throws SQLException {
        String sql = "UPDATE paydetail SET did = ?, mid = ?, gid = ?, dcount = ?, price = ?,  notes = ? WHERE did = ?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, payDetail.getDid());
            ps.setInt(2, payDetail.getMid());
            ps.setString(3, payDetail.getGid());
            ps.setInt(4, payDetail.getDcount());
            ps.setFloat(5, payDetail.getPrice());
            ps.setString(6, payDetail.getNotes());
            ps.setString(7, originalDid);

            ps.executeUpdate();
        } catch (SQLException e) {
            // 将异常直接抛出，由调用者处理
            throw e;
        }
    }

    public List<PayDetail> queryPayDetails(PayDetail criteria) {
        List<PayDetail> payDetailList = new ArrayList<>();
        StringBuilder sql = new StringBuilder("SELECT * FROM paydetail WHERE 1=1");
        List<Object> params = new ArrayList<>();

        // 根据criteria构建动态SQL和参数列表
        if (criteria.getDid() != 0) {
            sql.append(" AND Did = ?");
            params.add(criteria.getDid());
        }
        if (criteria.getMid() != 0) {
            sql.append(" AND Mid = ?");
            params.add(criteria.getMid());
        }
        if (criteria.getGid() != null && !criteria.getGid().isEmpty()) {
            sql.append(" AND Gid = ?");
            params.add(criteria.getGid());
        }
        if (criteria.getDcount() != 0) {
            sql.append(" AND Dcount = ?");
            params.add(criteria.getDcount());
        }
        if (criteria.getPrice() != 0f) {
            sql.append(" AND Price = ?");
            params.add(criteria.getPrice());
        }
        if (criteria.getGoodsTotal() != 0f) {
            sql.append(" AND GoodsTotal = ?");
            params.add(criteria.getGoodsTotal());
        }
        if (criteria.getNotes() != null && !criteria.getNotes().isEmpty()) {
            sql.append(" AND Notes LIKE ?");
            params.add("%" + criteria.getNotes() + "%"); // 使用LIKE进行模糊匹配
        }

        try (PreparedStatement ps = conn.prepareStatement(sql.toString())) {
            for (int i = 0; i < params.size(); i++) {
                ps.setObject(i + 1, params.get(i));
            }

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    PayDetail payDetail = new PayDetail();
                    payDetail.setDid(rs.getInt("Did"));
                    payDetail.setMid(rs.getInt("Mid"));
                    payDetail.setGid(rs.getString("Gid"));
                    payDetail.setDcount(rs.getInt("Dcount"));
                    payDetail.setPrice(rs.getFloat("Price"));
                    payDetail.setGoodsTotal(rs.getFloat("GoodsTotal"));
                    payDetail.setNotes(rs.getString("Notes"));
                    payDetailList.add(payDetail);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return payDetailList;
    }

    @Override
    public void close() throws Exception {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
}